#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
图形界面录音程序
功能：点击开始录音，点击停止并保存录音，录音完成后自动触发后续处理流程
"""

import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import threading
import os
from datetime import datetime
from audio_recorder import AudioRecorder
import subprocess
import sys

class GUIAudioRecorder:
    def __init__(self, root):
        self.root = root
        self.root.title("全自动录音摘要系统")
        self.root.geometry("500x450")
        self.root.resizable(False, False)
        
        # 初始化录音器
        self.recorder = AudioRecorder()
        self.output_file = None
        
        # 设置样式
        self.setup_styles()
        
        # 创建界面
        self.create_widgets()
        
        # 更新状态
        self.update_status()
        
    def setup_styles(self):
        """设置界面样式"""
        style = ttk.Style()
        style.theme_use('clam')
        
        # 配置按钮样式
        style.configure('Record.TButton', 
                       font=('Arial', 12, 'bold'),
                       foreground='white',
                       background='#4CAF50')
        
        style.configure('Stop.TButton',
                       font=('Arial', 12, 'bold'), 
                       foreground='white',
                       background='#f44336')
        
        style.configure('Normal.TButton',
                       font=('Arial', 10))
        
    def create_widgets(self):
        """创建界面组件"""
        # 主框架
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 标题
        title_label = ttk.Label(main_frame, text="🎤 全自动录音摘要系统", 
                               font=('Arial', 16, 'bold'))
        title_label.grid(row=0, column=0, columnspan=2, pady=(0, 20))
        
        # 状态显示
        self.status_label = ttk.Label(main_frame, text="准备就绪", 
                                     font=('Arial', 12))
        self.status_label.grid(row=1, column=0, columnspan=2, pady=(0, 10))
        
        # 录音时间显示
        self.time_label = ttk.Label(main_frame, text="00:00", 
                                   font=('Arial', 14, 'bold'),
                                   foreground='#2196F3')
        self.time_label.grid(row=2, column=0, columnspan=2, pady=(0, 20))
        
        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=3, column=0, columnspan=2, pady=(0, 20))
        
        # 开始录音按钮
        self.record_button = ttk.Button(button_frame, text="🎤 开始录音",
                                       style='Record.TButton',
                                       command=self.start_recording)
        self.record_button.grid(row=0, column=0, padx=(0, 10), ipadx=20, ipady=10)
        
        # 停止录音按钮
        self.stop_button = ttk.Button(button_frame, text="⏹️ 停止录音",
                                     style='Stop.TButton',
                                     command=self.stop_recording,
                                     state='disabled')
        self.stop_button.grid(row=0, column=1, padx=(10, 0), ipadx=20, ipady=10)
        
        # 设置框架
        settings_frame = ttk.LabelFrame(main_frame, text="设置", padding="10")
        settings_frame.grid(row=4, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 输出目录选择
        ttk.Label(settings_frame, text="保存目录:").grid(row=0, column=0, sticky=tk.W)
        
        # 设置默认保存目录为recordings文件夹
        recordings_dir = os.path.join(os.getcwd(), "recordings")
        # 确保recordings目录存在
        os.makedirs(recordings_dir, exist_ok=True)
        self.output_dir = tk.StringVar(value=recordings_dir)
        self.dir_label = ttk.Label(settings_frame, textvariable=self.output_dir,
                                  width=30, relief='sunken')
        self.dir_label.grid(row=0, column=1, padx=(5, 5), sticky=(tk.W, tk.E))
        
        ttk.Button(settings_frame, text="选择", style='Normal.TButton',
                  command=self.choose_directory).grid(row=0, column=2)
        
        # 采样率设置
        ttk.Label(settings_frame, text="采样率:").grid(row=1, column=0, sticky=tk.W, pady=(5, 0))
        
        self.sample_rate = tk.StringVar(value="16000")
        sample_rate_combo = ttk.Combobox(settings_frame, textvariable=self.sample_rate,
                                        values=["8000", "16000", "22050", "44100"],
                                        state="readonly", width=15)
        sample_rate_combo.grid(row=1, column=1, sticky=tk.W, padx=(5, 0), pady=(5, 0))
        sample_rate_combo.bind('<<ComboboxSelected>>', self.update_sample_rate)
        
        # 添加采样率说明标签
        ttk.Label(settings_frame, text="Hz", font=('Arial', 9)).grid(row=1, column=2, sticky=tk.W, padx=(2, 0), pady=(5, 0))
        
        # 自动处理选项
        self.auto_process = tk.BooleanVar(value=True)
        auto_check = ttk.Checkbutton(settings_frame, text="录音完成后自动处理", 
                                   variable=self.auto_process)
        auto_check.grid(row=2, column=0, columnspan=3, sticky=tk.W, pady=(5, 0))
        
        # 状态栏
        self.status_bar = ttk.Label(main_frame, text="就绪", relief='sunken')
        self.status_bar.grid(row=5, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(10, 0))
        
        # 配置网格权重
        main_frame.columnconfigure(1, weight=1)
        settings_frame.columnconfigure(1, weight=1)
        
    def start_recording(self):
        """开始录音"""
        try:
            # 更新录音器设置
            self.recorder.sample_rate = int(self.sample_rate.get())
            
            # 开始录音
            self.recorder.start_recording()
            
            # 更新界面状态
            self.record_button.config(state='disabled')
            self.stop_button.config(state='normal')
            self.status_label.config(text="🔴 录音中...", foreground='red')
            self.status_bar.config(text="录音进行中")
            
            # 开始计时
            self.start_time = datetime.now()
            self.update_timer()
            
        except Exception as e:
            messagebox.showerror("错误", f"开始录音失败：{str(e)}")
            
    def stop_recording(self):
        """停止录音并保存"""
        try:
            # 生成输出文件路径
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"recording_{timestamp}.wav"
            output_path = os.path.join(self.output_dir.get(), filename)
            
            # 停止录音并保存
            saved_file = self.recorder.stop_recording(output_path)
            
            if saved_file:
                # 更新界面状态
                self.record_button.config(state='normal')
                self.stop_button.config(state='disabled')
                self.status_label.config(text="✅ 录音已保存", foreground='green')
                self.status_bar.config(text=f"录音已保存到: {saved_file}")
                
                # 显示成功消息
                messagebox.showinfo("成功", f"录音已保存到：\n{saved_file}")
                
                # 如果启用自动处理，则启动后续流程
                if self.auto_process.get():
                    self.start_auto_processing(saved_file)
            else:
                messagebox.showerror("错误", "保存录音失败")
                
        except Exception as e:
            messagebox.showerror("错误", f"停止录音失败：{str(e)}")
            
    def start_auto_processing(self, audio_file):
        """启动自动处理流程"""
        try:
            # 导入自动化工作流程模块
            from automation_workflow import AutomationWorkflow
            
            self.status_label.config(text="🔄 正在自动处理...", foreground='orange')
            self.status_bar.config(text="正在进行语音识别和摘要生成...")
            
            # 创建工作流程实例
            workflow = AutomationWorkflow()
            
            # 检查工作流程状态
            status = workflow.get_status()
            if not status["speech_recognizer_ready"]:
                messagebox.showerror("错误", "语音识别器未就绪，请检查DASHSCOPE_API_KEY配置")
                return
            
            if not status["llm_processor_ready"]:
                messagebox.showerror("错误", "大模型处理器未就绪，请检查LLM相关配置")
                return
            
            # 在新线程中执行自动处理，避免阻塞UI
            processing_thread = threading.Thread(
                target=self.run_auto_processing, 
                args=(audio_file, workflow)
            )
            processing_thread.daemon = True
            processing_thread.start()
            
        except ImportError as e:
            messagebox.showerror("错误", f"无法导入自动化模块: {str(e)}")
        except Exception as e:
            messagebox.showerror("错误", f"启动自动处理失败：{str(e)}")
            self.status_label.config(text="❌ 自动处理失败", foreground='red')
            
    def run_auto_processing(self, audio_file, workflow):
        """运行自动处理流程"""
        try:
            # 执行自动化处理
            result = workflow.process_audio_file(audio_file)
            
            # 在主线程中更新UI
            self.root.after(0, lambda: self.on_automation_complete(result))
            
        except Exception as e:
            error_msg = f"自动化处理异常: {str(e)}"
            self.root.after(0, lambda: self.on_automation_error(error_msg))
    
    def on_automation_complete(self, result):
        """自动化处理完成的回调"""
        if result.get("status") == "success":
            # 获取处理结果信息
            steps = result.get("steps", {})
            llm_result = steps.get("llm_processing", {})
            title = llm_result.get("title", "未知标题")
            
            success_msg = f"✅ 自动化处理完成！\n\n"
            success_msg += f"📝 生成标题: {title}\n"
            
            if steps.get("feishu_push", {}).get("status") == "success":
                success_msg += f"📤 已成功推送到飞书\n"
            elif steps.get("feishu_push", {}).get("status") == "skipped":
                success_msg += f"📤 跳过飞书推送\n"
            else:
                success_msg += f"📤 飞书推送失败\n"
            
            success_msg += f"\n📁 摘要文件: {os.path.basename(result.get('summary_file', ''))}"
            
            self.status_label.config(text="✅ 自动处理完成", foreground='green')
            self.status_bar.config(text="录音已完成转录、摘要生成和飞书推送")
            messagebox.showinfo("处理完成", success_msg)
        else:
            error_msg = f"❌ 自动化处理失败\n\n错误信息: {result.get('error', '未知错误')}"
            self.status_label.config(text="❌ 自动处理失败", foreground='red')
            self.status_bar.config(text=f"处理失败：{result.get('error', '未知错误')}")
            messagebox.showerror("处理失败", error_msg)
    
    def on_automation_error(self, error_msg):
        """自动化处理错误的回调"""
        self.status_label.config(text="❌ 自动处理失败", foreground='red')
        self.status_bar.config(text=error_msg)
        messagebox.showerror("处理异常", error_msg)
            
    def update_timer(self):
        """更新录音时间显示"""
        if self.recorder.is_recording():
            elapsed = datetime.now() - self.start_time
            minutes = int(elapsed.total_seconds() // 60)
            seconds = int(elapsed.total_seconds() % 60)
            self.time_label.config(text=f"{minutes:02d}:{seconds:02d}")
            
            # 每秒更新一次
            self.root.after(1000, self.update_timer)
        else:
            self.time_label.config(text="00:00")
            
    def choose_directory(self):
        """选择保存目录"""
        directory = filedialog.askdirectory(initialdir=self.output_dir.get())
        if directory:
            self.output_dir.set(directory)
            
    def update_sample_rate(self, event=None):
        """更新采样率设置"""
        if not self.recorder.is_recording():
            self.recorder.sample_rate = int(self.sample_rate.get())
            self.status_bar.config(text=f"采样率已设置为: {self.sample_rate.get()} Hz")
            
    def play_audio(self, file_path):
        """播放音频文件"""
        try:
            import subprocess
            import platform
            
            system = platform.system()
            if system == "Windows":
                os.startfile(file_path)
            elif system == "Darwin":  # macOS
                subprocess.run(["open", file_path])
            else:  # Linux
                subprocess.run(["xdg-open", file_path])
                
        except Exception as e:
            messagebox.showwarning("警告", f"无法播放音频文件：{str(e)}")
            
    def update_status(self):
        """更新状态显示"""
        try:
            # 检查录音设备
            devices = self.recorder.get_available_devices()
            if devices is not None:
                self.status_bar.config(text="录音设备正常")
            else:
                self.status_bar.config(text="警告：未检测到录音设备")
        except Exception as e:
            self.status_bar.config(text=f"设备检查失败：{str(e)}")
            
    def on_closing(self):
        """程序关闭时的处理"""
        if self.recorder.is_recording():
            if messagebox.askokcancel("退出", "正在录音中，确定要退出吗？"):
                self.recorder.stop_recording()
                self.root.destroy()
        else:
            self.root.destroy()

def main():
    """主函数"""
    root = tk.Tk()
    app = GUIAudioRecorder(root)
    
    # 设置关闭事件处理
    root.protocol("WM_DELETE_WINDOW", app.on_closing)
    
    # 居中显示窗口
    root.update_idletasks()
    x = (root.winfo_screenwidth() // 2) - (root.winfo_width() // 2)
    y = (root.winfo_screenheight() // 2) - (root.winfo_height() // 2)
    root.geometry(f"+{x}+{y}")
    
    # 启动主循环
    root.mainloop()

if __name__ == "__main__":
    main()